﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Threading;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using Board1.GetData;
using Board1.Info;
using System.ComponentModel;
namespace Board1
{
    public partial class AlbumPage : PhoneApplicationPage, INotifyPropertyChanged
    {
        private int index;
        public static int pageID = 1;
        WebClient download = new WebClient();
        string webData;
        private ObservableCollection<AlbumData> listAlbum;

        private static ObservableCollection<ZingSong> _listResult;
        public static ObservableCollection<ZingSong> ListResult
        { get { return _listResult; } }
        public AlbumPage()
        {
            InitializeComponent();
            index = MainPage.indexAlbumSelected;
            listAlbum = DataBoard200.TopHot200Albums;
            DataContext = listAlbum[index];
        }
        // bat su kien flick trong trang
        private void GestureListener_Flick_1(object sender, FlickGestureEventArgs e)
        {
            //left
            if (e.HorizontalVelocity >= 0)
            {
                if (index > 0)
                {
                    index--;
                }
                else
                {
                    index = listAlbum.Count - 1;
                }

            }
            //right
            else
            {
                if (index < listAlbum.Count - 1)
                {
                    index++;
                }
                else
                {
                    index = 0;
                }
            }
            DataContext = listAlbum[index];
        }

        //bat su kien khi click vao app bar
        private void appBarZingMP3_Click(object sender, EventArgs e)
        {
            _listResult = new ObservableCollection<ZingSong>();
            string keyWord = (listAlbum[index].albumName+"+"+listAlbum[index].albumArtist).Replace(" ", "+");
            webData = null;
            LoadingState(true);
            ThreadPool.QueueUserWorkItem(o =>
                {
                    Dispatcher.BeginInvoke(new Action(() => DownloadData(keyWord)));
                    Dispatcher.BeginInvoke(new Action(() => LoadingState(false)));
                    Thread.Sleep(3000);
                }
                );
            //DownloadData(keyWord);
        }

        // tai noi dung tim kiem html
        private void DownloadData(string key)
        {
            key = "http://mp3.zing.vn/tim-kiem/playlist.html?q=" + key;
            try
            {
                download.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallBack);
                download.DownloadStringAsync(new Uri(key));
            }
            catch (System.Exception)
            {
                MessageBox.Show("Internet Connection Error","Error", MessageBoxButton.OK);
            }
        }
        private void DownloadStringCallBack(object sender, DownloadStringCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null)
            {
                webData = (string)e.Result;
                HtmlHander(webData);
                Board1.UIPage.ListResultSong.PageID = pageID;
                this.NavigationService.Navigate(new Uri("/UIPage/ListResultSong.xaml", UriKind.Relative));
            }
            else 
            {
                MessageBox.Show("Internet Connection Error", "Error", MessageBoxButton.OK);
            }
        }

        //xu li file html de dua ra danh sach tim kiem
        private void HtmlHander(string data)
        {
            MatchCollection content = Regex.Matches(data, "<h3>(.*?)<a title=\"(.*?)\" href=\"(.*?)\">(.*?)</a>(.*?)</h3>", RegexOptions.Singleline | RegexOptions.IgnoreCase);
            foreach (Match m in content)
            {
                ZingSong newItem = new ZingSong();
                string name = m.Groups[2].ToString().Replace("\"", "");
                newItem.song = name.Replace("&amp;", "&");
                string artist = m.Groups[4].ToString().Replace("\"", "");
                newItem.artist = artist.Replace("&amp;", "&");
                string link = "http://mp3.zing.vn" + m.Groups[3].ToString().Replace("\"", "");
                newItem.link = link;
                _listResult.Add(newItem);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            var tempEvent = PropertyChanged;
            if (tempEvent != null)
            {
                tempEvent(this, e);
            }
        }

        private void LoadingState(bool e)
        {
            if (e)
            {
                LoadState1.Visibility = Visibility.Visible;
                LoadBar1.Visibility = Visibility.Visible;
                LoadBar1.IsIndeterminate = e;
            }
            else
            {
                LoadState1.Visibility = Visibility.Collapsed;
                LoadBar1.Visibility = Visibility.Collapsed;
                LoadBar1.IsIndeterminate = e;
            }
        }
    }
}